package ae.pcfc.cldos.online.common.messaging;

import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.listener.SessionAwareMessageListener;

import ae.pcfc.cldos.online.common.manager.FileStorageManager;
import ae.pcfc.cldos.online.common.manager.provider.FileStorageManagerImpl.FileStorage;
import ae.pcfc.cldos.online.common.vo.FileVO;

/**
 * 
 * @author arosa
 *
 */
public class NetFileTransferListener extends BaseMessageListener implements SessionAwareMessageListener<Message> {
 
	private FileStorageManager fileStorageManager;
	
	public void setFileStorageManager(FileStorageManager fileStorageManager) {
		this.fileStorageManager = fileStorageManager;
	}
	
	public void onMessage(Message message, Session session) throws JMSException {
		@SuppressWarnings("unchecked")
		List<FileVO> fileVOs = (List<FileVO>)getMessageConverter().fromMessage(message);
		Stack<FileVO> transfered = new Stack<FileVO>();
		for (Iterator<FileVO> iterator = fileVOs.iterator(); iterator.hasNext();) {
			FileVO fileVO = (FileVO) iterator.next();
			try{
				Long id = fileStorageManager.transferToDotNet(fileVO);
				fileVO.setId(id);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (Exception e) {
				while(!transfered.empty()){
					FileVO toDelete = transfered.pop();
					fileStorageManager.deleteFromStorage(toDelete.getId(), 
							toDelete.getFileExt(), toDelete.getAttachmentTypeCode(), FileStorage.DOT_NET_STORAGE);
				}
				StringBuilder sb = new StringBuilder();
				sb.append("File "+fileVO+" Transfer not completed" +
						"with reason ");
				StackTraceElement[] stelems = e.getStackTrace();
				for (int i = 0; i < stelems.length; i++) {
					sb.append(stelems[i].toString()+"\n");
					System.out.println();
				}
				e.printStackTrace();
				throw new JMSException(sb.toString());
				
			}
		}
	}

}
